﻿using FineUIPro;
using KPI_SYSTEM.Code;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace KPI_SYSTEM.DictPage
{
    public partial class User_Dict : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Server.ScriptTimeout = 10000;
            if (!IsPostBack)
            {
               
                LoadBaseData();
                BindData(); 
            }
            PublicMethod.GetApprovalButton("User_Dict.aspx", Toolbar2, Grid1);
        }
        /// <summary>
        /// 加载页面必备数据
        /// </summary>
        private void LoadBaseData()
        {
            DataTable tableDept = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT DING_CODE,DEPT_NAME FROM DEPT_DICT WHERE  DEPT_STATUS=1").Tables[0];
            ddlSearchDept.DataTextField = "DEPT_NAME";
            ddlSearchDept.DataValueField = "DING_CODE";
            ddlSearchDept.DataSource = tableDept;
            ddlSearchDept.DataBind();
            FineUIPro.ListItem searchDeptItem = new FineUIPro.ListItem();
            searchDeptItem.Value = "0";
            searchDeptItem.Text = "全部";
            ddlSearchDept.Items.Insert(0, searchDeptItem);

            ddlFormUSER_DEPT.DataTextField = "DEPT_NAME";
            ddlFormUSER_DEPT.DataValueField = "DING_CODE";
            ddlFormUSER_DEPT.DataSource = tableDept;
            ddlFormUSER_DEPT.DataBind();


            DataTable tableRole = SqlHelper.ExecuteDataset(CommandType.Text, @"SELECT ROLE_CODE,ROLE_NAME FROM ROLE_DICT WHERE STATUS=1").Tables[0];
            ddlFormUSER_ROLE.DataTextField = "ROLE_NAME";
            ddlFormUSER_ROLE.DataValueField = "ROLE_CODE";
            ddlFormUSER_ROLE.DataSource = tableRole;
            ddlFormUSER_ROLE.DataBind();

        }
        /// <summary>
        /// 加载页面列表数据
        /// </summary>
        private void BindData()
        {
            StringBuilder sqlWhere = new StringBuilder();
            String mainDataSql = @"SELECT A.REC_ID,A.USER_ID,A.USER_CODE,A.USER_NAME,A.USER_SEX,A.USER_AGE,A.USER_TYPE,A.USER_DEPT,A.USER_PHONE,A.USER_PASSWORD,A.DING_USER_ID,A.USER_REMARK,
                                    A.USER_ROLE,A.USER_STATUS,A.CREATE_TIME,A.CREATE_USER,A.UPDATE_TIME,A.UPDATE_USER,
                                    CASE WHEN A.USER_STATUS=1 THEN '启用' WHEN A.USER_STATUS=0 THEN '停用' END AS USER_STATUS_NAME,
                                    (SELECT ROLE_NAME FROM ROLE_DICT WHERE ROLE_CODE = A.USER_ROLE) AS USER_ROLE_NAME,
                                    (SELECT DEPT_NAME FROM DEPT_DICT WHERE DING_CODE = A.USER_DEPT) AS USER_DEPT_NAME
                                    FROM USER_DICT AS A WHERE 1=1 {0}";
            if (tbxNameSerach.Text.Trim() != "")
            {
                sqlWhere.Append(" AND A.USER_NAME LIKE '%" + tbxNameSerach.Text.Trim() + "%'");
            }
            if (tbxCodeSerach.Text.Trim() != "")
            {
                sqlWhere.Append(" AND A.USER_CODE LIKE '%" + tbxCodeSerach.Text.Trim() + "%'");
            }
            if (ddlSearchDept.SelectedValue != "0" && ddlSearchDept.SelectedValue != null)
            {
                sqlWhere.Append(" AND A.USER_DEPT = " + ddlSearchDept.SelectedValue);
            }
            mainDataSql = string.Format(mainDataSql, sqlWhere.ToString());
            DataTable mainDataTable = SqlHelper.ExecuteDataset(CommandType.Text, mainDataSql).Tables[0];
            Grid1.DataSource = mainDataTable;
            Grid1.DataBind();
        }
        // 根据行ID来删除行数据
        private void DeleteRowByID(int rowID)
        {
            try
            {
                SqlHelper.ExecuteNonQuery(CommandType.Text, "DELETE FROM USER_DICT WHERE REC_ID=" + rowID);
            }
            catch (Exception ex)
            {
                throw new Exception("删除失败！");
            }
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[e.RowIndex][0]);
                try
                {
                    DeleteRowByID(rowID);
                    BindData();
                    ShowNotify("删除数据成功!");

                }
                catch (Exception ex)
                {
                    ShowNotify("删除数据失败!");
                }
            }
        }
        protected void Grid1_PreRowDataBound(object sender, GridPreRowEventArgs e)
        {
            // 如果绑定到 DataTable，那么这里的 DataItem 就是 DataRowView
            DataRowView row = e.DataItem as DataRowView;
            int rowId = Convert.ToInt32(row["REC_ID"]);

            LinkButtonField editField = Grid1.FindColumn("Edit") as LinkButtonField;
            editField.OnClientClick = String.Format("showEditWindow('{0}');", rowId);
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            book = PublicMethod.NPOIExcel(Grid1);
            MemoryStream ms = new MemoryStream();
            book.Write(ms);
            Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode("人员列表", System.Text.Encoding.UTF8)));
            Response.BinaryWrite(ms.ToArray());
            Response.End();
            book = null;
            ms.Close();
            ms.Dispose();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<String, String> keyValuePairs = new Dictionary<string, string>();
                keyValuePairs.Clear();
                if (tbxFormUSER_NAME.Text.Trim() != "")
                {
                    keyValuePairs.Add("USER_NAME", tbxFormUSER_NAME.Text.Trim());
                }
                else
                {
                    ShowNotify("人员姓名不能为空!");
                    return;
                }
                if (tbxFormUSER_CODE.Text.Trim() != "")
                {
                    keyValuePairs.Add("USER_CODE", tbxFormUSER_CODE.Text.Trim());
                }
                else
                {
                    ShowNotify("人员编码不能为空!");
                    return;
                }
                //if (ddlFormUSER_SEX.SelectedValue != "" && ddlFormUSER_SEX.SelectedValue != null)
                //{
                //    keyValuePairs.Add("USER_SEX", ddlFormUSER_SEX.SelectedValue);
                //}
                //if (tbxFormUSER_AGE.Text.Trim() != "")
                //{
                //    keyValuePairs.Add("USER_AGE", tbxFormUSER_AGE.Text.Trim());
                //}
                //if (ddlFormUSER_TYPE.SelectedValue != "" && ddlFormUSER_TYPE.SelectedValue != null)
                //{
                //    keyValuePairs.Add("USER_TYPE", ddlFormUSER_TYPE.SelectedValue);
                //}
                if (ddlFormUSER_DEPT.SelectedValue != "" && ddlFormUSER_DEPT.SelectedValue != null)
                {
                    keyValuePairs.Add("USER_DEPT", ddlFormUSER_DEPT.SelectedValue);
                }
                if (tbxFormUSER_PHONE.Text.Trim() != "")
                {
                    keyValuePairs.Add("USER_PHONE", tbxFormUSER_PHONE.Text.Trim());
                }
                keyValuePairs.Add("USER_PASSWORD", PublicMethod.GetMD5Hash(tbxFormUSER_CODE.Text.Trim() + "@123456"));
                if (tbxFormDING_USER_ID.Text.Trim() != "")
                {
                    keyValuePairs.Add("DING_USER_ID", tbxFormDING_USER_ID.Text.Trim());
                }
                if (tbxFormUSER_REMARK.Text.Trim() != "")
                {
                    keyValuePairs.Add("USER_REMARK", tbxFormUSER_REMARK.Text.Trim());
                }
                if (ddlFormUSER_ROLE.SelectedValue != "" && ddlFormUSER_ROLE.SelectedValue != null)
                {
                    keyValuePairs.Add("USER_ROLE", ddlFormUSER_ROLE.SelectedValue);
                }
                if (ddlFormUSER_STATUS.SelectedValue != "" && ddlFormUSER_STATUS.SelectedValue != null)
                {
                    keyValuePairs.Add("USER_STATUS", ddlFormUSER_STATUS.SelectedValue);
                }
                String strRowID = hfFormID.Text;
                if (String.IsNullOrEmpty(strRowID))
                {
                    keyValuePairs.Add("CREATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("CREATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM USER_DICT WHERE 1=2", "Add", keyValuePairs);

                    ShowNotify("保存成功!");
                }
                else
                {
                    keyValuePairs.Add("REC_ID", strRowID);
                    keyValuePairs.Add("UPDATE_TIME", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    keyValuePairs.Add("UPDATE_USER", Session["UserID"].ToString());
                    PublicMethod.SetDataMethod("SELECT * FROM USER_DICT WHERE REC_ID=" + strRowID, "Update", keyValuePairs);
                    ShowNotify("保存成功!");
                }
                // 重新绑定表格，并点击当前编辑或者新增的行
                BindData();
                PageContext.RegisterStartupScript(String.Format("F('{0}').selectRow('{1}');", Grid1.ClientID, "1") + Window1.GetHideReference());
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }

        }
        protected void btnSyncUser_Click(object sender, EventArgs e)
        {

            try
            {
                labldingding.Text = "正在同步，请稍后......";
                List<DING_USER_INFO> dING_USER_INFOs = new List<DING_USER_INFO>();
                dING_USER_INFOs = DingHelper.GetUserList();
               
                foreach (DING_USER_INFO dING_USER_INFO  in dING_USER_INFOs)
                {
                    StringBuilder sqlUpdate = new StringBuilder();
                    StringBuilder sqlInsert = new StringBuilder();
                    int checkCount = (int)SqlHelper.ExecuteScalar(CommandType.Text, "SELECT COUNT(*) FROM USER_DICT WHERE  DING_USER_ID='" + dING_USER_INFO.USER_DING_ID + "'");
                    if (checkCount > 0)
                    {
                        sqlUpdate.Append("UPDATE USER_DICT SET USER_NAME='" + dING_USER_INFO.USER_NAME + "',USER_CODE='"+ dING_USER_INFO.USER_CODE + "', " +
                                         "USER_POSITION='"+ dING_USER_INFO.USER_POSITION+ "',USER_PHONE='"+ dING_USER_INFO.USER_PHONE + "', " +
                                         "USER_DEPT='"+ dING_USER_INFO.USER_DEPT + "' " +
                                         "WHERE DING_USER_ID='" + dING_USER_INFO.USER_DING_ID + "';");
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate.ToString());
                    }
                    else
                    {
                        
                        sqlInsert.Append("INSERT INTO USER_DICT (USER_CODE,USER_POSITION,USER_NAME,USER_DEPT,USER_PHONE,USER_PASSWORD,DING_USER_ID,USER_ROLE,USER_STATUS) VALUES " +
                                        "('"+ dING_USER_INFO.USER_CODE + "','"+ dING_USER_INFO.USER_POSITION + "','"+ dING_USER_INFO.USER_NAME + "','"+ dING_USER_INFO.USER_DEPT + "'," +
                                        "'"+ dING_USER_INFO.USER_PHONE + "','" + PublicMethod.GetMD5Hash(dING_USER_INFO.USER_CODE + "@123456") + "','"+ dING_USER_INFO.USER_DING_ID + "'," +
                                        "'"+ dING_USER_INFO.USER_ROLE + "',1);");
                       
                        SqlHelper.ExecuteNonQuery(CommandType.Text, sqlInsert.ToString());
                    }
                }
                labldingding.Text = "同步已完成，正在刷新数据......";
                BindData();
                PageContext.RegisterStartupScript(Window2.GetHideReference());
               
                
            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }
        }

        protected void btnSyncPerson_Click(object sender, EventArgs e)
        {

            try
            {
                if (Grid1.SelectedRowIndexArray.Length > 0)
                {
                    StringBuilder sqlUpdate = new StringBuilder();
                    GridRow gridRow = Grid1.SelectedRow;
                    String userID = gridRow.Values[2].ToString();
                    DING_USER_INFO dING_USER_INFO = DingHelper.GetUserDetailMessage(userID);
                    sqlUpdate.Append("UPDATE USER_DICT SET USER_NAME='" + dING_USER_INFO.USER_NAME + "',USER_CODE='" + dING_USER_INFO.USER_CODE + "', " +
                                        "USER_POSITION='" + dING_USER_INFO.USER_POSITION + "',USER_PHONE='" + dING_USER_INFO.USER_PHONE + "', " +
                                        "USER_DEPT='" + dING_USER_INFO.USER_DEPT + "' " +
                                        "WHERE DING_USER_ID='" + dING_USER_INFO.USER_DING_ID + "';");
                    SqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate.ToString());

                }
                else
                {
                    ShowNotify("未选中任何行!");
                }


            }
            catch (Exception ex)
            {

                throw new Exception("保存失败！");
            }
        }
        
    }
}